package com.chookss.home.audit.clockIn;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.audit.ApprovalProcessActivity;
import com.chookss.home.audit.adapter.ClockInProcessAdapter;
import com.chookss.home.entity.ClockInDetailEntity;
import com.chookss.home.entity.ClockInRecordEntity;
import com.chookss.home.entity.ProcessEntity;
import com.chookss.home.entity.WorkNewEntity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.CircleImageView;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ClockInReissueCardDetailActivity extends BaseAct {
    //补卡详情页
    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.tvKaoqin)
    TextView tvKaoqin;
    @BindView(R.id.tvGroup)
    TextView tvGroup;
    @BindView(R.id.tvTime)
    TextView tvTime;
    @BindView(R.id.tvStatus)
    TextView tvStatus;
    @BindView(R.id.tvRemark)
    TextView tvRemark;
    @BindView(R.id.llBottom)
    LinearLayout llBottom;
    @BindView(R.id.viewRemark)
    View viewRemark;
    @BindView(R.id.llRemark)
    LinearLayout llRemark;
    @BindView(R.id.tvSure)
    TextView tvSure;
    @BindView(R.id.tvCancel)
    TextView tvCancel;
    @BindView(R.id.common_right_txt)
    TextView common_right_txt;
    @BindView(R.id.llProcess)
    LinearLayout llProcess;
    @BindView(R.id.ivHead)
    CircleImageView ivHead;
    @BindView(R.id.tvProcessTitle)
    TextView tvProcessTitle;
    @BindView(R.id.tvProcessTitleInit)
    TextView tvProcessTitleInit;
    @BindView(R.id.tvProcessStatus)
    TextView tvProcessStatus;
    @BindView(R.id.emptyProcess)
    View emptyProcess;
    @BindView(R.id.emptyBottom)
    View emptyBottom;
    @BindView(R.id.llProcessTop)
    LinearLayout llProcessTop;
    @BindView(R.id.llAudit)
    LinearLayout llAudit;
    @BindView(R.id.edAudit)
    EditText edAudit;
    private WorkNewEntity workNewEntity = null;
    private ClockInRecordEntity clockInRecordEntity = null;
    private ClockInProcessAdapter adapter;
    private List<ProcessEntity> list = new ArrayList<>();
    private ProcessEntity endProcessEntity = null;
    private ClockInDetailEntity clockInDetailEntity = null;
    private int shangbanCd = 1;//1上班0下班
    private boolean isRecord = false;//默认是待审批页面过来的
    private String workflowId = "", projectCode = "";
    private int type = 3;//3补卡 5外勤

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clock_in_reissue_card_detail);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        type = getIntent().getIntExtra("type", 3);
        isRecord = getIntent().getBooleanExtra("isRecord", false);
        common_right_txt.setText("审批流程");
        common_right_txt.setVisibility(View.VISIBLE);
        if (isRecord) {
            //考勤记录列表进来的
            clockInRecordEntity = (ClockInRecordEntity) getIntent().getSerializableExtra("clockInRecordEntity");
            shangbanCd = getIntent().getIntExtra("shangbanCd", 1);
            if (clockInRecordEntity != null) {
                if (shangbanCd == 1) {
                    //上班
                    if (type == 5) {
                        commonTitleTxt.setText(clockInRecordEntity.getEmployeeName() + "的外勤申请");
                    } else {
                        commonTitleTxt.setText(clockInRecordEntity.getEmployeeName() + "的补卡申请");
                    }
                } else {
                    //下班
                    if (type == 5) {
                        commonTitleTxt.setText(clockInRecordEntity.getEmployeeName() + "的外勤申请");
                    } else {
                        commonTitleTxt.setText(clockInRecordEntity.getEmployeeName() + "的补卡申请");
                    }
                }

                selectKaoqinDeail();
            }
        } else {
            //审批工作流进来的
            workNewEntity = (WorkNewEntity) getIntent().getSerializableExtra("data");
            if (workNewEntity != null) {
                if (type == 5) {
                    shangbanCd = -1;
                } else {
                    if (!Utils.isNull(workNewEntity.getParams().getStartTime())) {
                        //说明补卡的是上午
                        shangbanCd = 1;
                    } else {
                        shangbanCd = 0;
                    }
                }

                commonTitleTxt.setText(workNewEntity.getProjectName());
                selectKaoqinDeail();
            }
        }
    }

    private void selectKaoqinDeail() {
        //审批基本数据
        Map<String, String> map = new HashMap<>();
        if (isRecord) {
            //考勤记录列表进来的
            map.put("projectCode", clockInRecordEntity.getId());
        } else {
            map.put("projectCode", workNewEntity.getProjectCode());
        }
        map.put("type", type + "");//3补卡 4请假
        if (shangbanCd >= 0) {
            map.put("shangbanCd", shangbanCd + "");//3补卡 4请假
        }
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<ClockInDetailEntity>>() {
        }.getType(), null, Urls.selectKaoqinDeail, SignUtils2.makeSignStr(map), false, new ObserverCallback<ClockInDetailEntity>() {
            @Override
            public void onSuccess(ClockInDetailEntity data) {
                if (data != null) {
                    if (tvStatus == null) {
                        return;
                    }
                    workflowId = data.getWorkflowId();
                    projectCode = data.getProjectCode();
                    clockInDetailEntity = data;
                    if (!Utils.isNull(data.getShangbanBukaAuditCd()) || "1".equals(data.getWaiqinCd())) {
                        shangbanCd = 1;
                        tvKaoqin.setText(data.getKaoqinGroupName() + "(" + data.getKaoqinGroupCode() + ")");
                        tvGroup.setText(data.getItemGroupName() + "(" + ClockInUtils.getGroupEnd(data.getItemGroupCode()) + ")");
                        if (type == 5) {
                            tvStatus.setText("上班外勤打卡");
                            if (!Utils.isNull(data.getStartTime())) {
                                tvTime.setText(data.getStartTime());
                            } else {
                                tvTime.setText(data.getBukaStartTime());
                            }
                            if (!Utils.isNull(data.getShangbanWaiqinRemark())) {
                                tvRemark.setText(data.getShangbanWaiqinRemark());
                                llRemark.setVisibility(View.VISIBLE);
                                viewRemark.setVisibility(View.VISIBLE);
                            } else {
                                llRemark.setVisibility(View.GONE);
                                viewRemark.setVisibility(View.GONE);
                            }

                            viewRemark.setVisibility(View.GONE);
                        } else {
                            tvStatus.setText("上班补卡");
                            tvTime.setText(data.getBukaStartTime());
                            if (Utils.isNull(data.getShangbanBukaRemark())) {
                                tvRemark.setText("无");
                            } else {
                                tvRemark.setText(data.getShangbanBukaRemark());
                            }
                            llRemark.setVisibility(View.VISIBLE);
                            viewRemark.setVisibility(View.VISIBLE);
                        }
//                        if ("1".equals(data.getShangbanBukaAuditCd()) || "3".equals(data.getXiabanBukaAuditCd()) || ("1".equals(data.getWaiqinCd()) || "3".equals(data.getWaiqinCd()))) {
//                            //0待审核1审核通过2未通过3废弃
//                            llBottom.setVisibility(View.GONE);
//                        } else {
                        //0么有权限1有2展示废弃修改
                        if (Utils.isNull(data.getAuditFlag())) {
                            llBottom.setVisibility(View.GONE);
                            getProcessData();
                        } else {
                            if ("1".equals(data.getAuditFlag()) || "2".equals(data.getAuditFlag())) {
                                llBottom.setVisibility(View.VISIBLE);
                                if ("2".endsWith(data.getAuditFlag())) {
                                    tvSure.setText("修改");
                                    tvCancel.setText("废弃");
                                }else{
                                    llAudit.setVisibility(View.VISIBLE);
                                }
                            } else {
                                llBottom.setVisibility(View.GONE);
                                getProcessData();
                            }
                        }
//                        }
                    } else {
                        shangbanCd = 0;
                        tvKaoqin.setText(data.getXianbanKaoqinGroupName() + "(" + data.getXiabanKaoqinGroupCode() + ")");
                        tvGroup.setText(data.getXiabanItemGroupName() + "(" + data.getXiabanItemGroupCode() + ")");
                        if (type == 5) {
                            tvStatus.setText("下班外勤打卡");
                            if (!Utils.isNull(data.getEndTime())) {
                                tvTime.setText(data.getEndTime());
                            } else {
                                tvTime.setText(data.getBukaEndTime());
                            }
                            if (!Utils.isNull(data.getXiabanWaiqinRemark())) {
                                tvRemark.setText(data.getXiabanWaiqinRemark());
                                llRemark.setVisibility(View.VISIBLE);
                                viewRemark.setVisibility(View.VISIBLE);
                            } else {
                                llRemark.setVisibility(View.GONE);
                                viewRemark.setVisibility(View.GONE);
                            }
                        } else {
                            tvStatus.setText("下班补卡");
                            tvTime.setText(data.getBukaEndTime());
                            if (Utils.isNull(data.getXiabanBukaRemark())) {
                                tvRemark.setText("无");
                            } else {
                                tvRemark.setText(data.getXiabanBukaRemark());
                            }
                            llRemark.setVisibility(View.VISIBLE);
                            viewRemark.setVisibility(View.VISIBLE);
                        }
//                        if ("1".equals(data.getXiabanBukaAuditCd()) || "3".equals(data.getXiabanBukaAuditCd()) || ("1".equals(data.getXiabanWaiqinCd()) || "3".equals(data.getXiabanWaiqinCd()))) {
//                            //0待审核1审核通过2未通过3废弃
//                            llBottom.setVisibility(View.GONE);
//                        } else {
                        //0么有权限1有2展示废弃修改
                        if (Utils.isNull(data.getAuditFlag())) {
                            llBottom.setVisibility(View.GONE);
                        } else {
                            if ("1".equals(data.getAuditFlag()) || "2".equals(data.getAuditFlag())) {
                                llBottom.setVisibility(View.VISIBLE);
                                if ("2".endsWith(data.getAuditFlag())) {
                                    tvSure.setText("修改");
                                    tvCancel.setText("废弃");
                                }else{
                                    llAudit.setVisibility(View.VISIBLE);
                                }
                            } else {
                                llBottom.setVisibility(View.GONE);
                            }
                        }
//                        }

                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }
    private void getProcessData() {
        //审批进度
        Map<String, String> map = new HashMap<>();
        map.put("projectCode", projectCode);
        map.put("type", type + "");
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<ProcessEntity>>>() {
        }.getType(), null, Urls.selectAuditDetailList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<ProcessEntity>>() {
            @Override
            public void onSuccess(List<ProcessEntity> data) {
                String name = "", headUrl = "";
                List<ProcessEntity> processEntityList = new ArrayList<>();
                for (int i = 0; i < data.size(); i++) {
                    processEntityList.add(data.get(i));
                    if (data.get(i).getConnectType().equals("0")) {
                        name = data.get(i).getCreateEmployeeName();
                        headUrl = data.get(i).getHeadPhotoThumbUrl();
                    }
                    if (data.get(i).getEndStep().equals("1")) {
                        ProcessEntity endProcessEntity = new ProcessEntity();
                        if (Utils.isNull(name)) {
                            endProcessEntity.setCreateEmployeeName(data.get(0).getCreateEmployeeName());
                            endProcessEntity.setRealAuditEmployeeName(data.get(0).getCreateEmployeeName());
                        } else {
                            endProcessEntity.setCreateEmployeeName(name);
                            endProcessEntity.setRealAuditEmployeeName(name);
                        }
                        if (Utils.isNull(headUrl)) {
                            endProcessEntity.setHeadPhotoThumbUrl(data.get(0).getHeadPhotoThumbUrl());
                        } else {
                            endProcessEntity.setHeadPhotoThumbUrl(headUrl);
                        }
                        endProcessEntity.setConnectType("0");
                        endProcessEntity.setEndProcess(true);
                        endProcessEntity.setAuditStatus("1");
                        processEntityList.add(endProcessEntity);
                    }
                }
                if (data.size() > 0) {
                    llProcess.setVisibility(View.VISIBLE);
                    emptyProcess.setVisibility(View.VISIBLE);
                    setProcessDetail(processEntityList.get(processEntityList.size() - 1));
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void setProcessDetail(ProcessEntity entity) {
        if (!Utils.isNull(entity.getHeadPhotoThumbUrl())) {
            GlideUtils.loadAvatar(this, entity.getHeadPhotoThumbUrl(), ivHead);
        } else {
            GlideUtils.loadAvatar(this, new ShareUtils().getString(this, StaticClass.ORIGINALURL, ""), ivHead);
        }
        if (entity.isEndProcess()) {
            //已结束
            llProcessTop.setVisibility(View.GONE);
            tvProcessStatus.setText("已结束");
            tvProcessStatus.setTextColor(Color.parseColor("#00C993"));
        } else {
            //getWorkFlowName  环节名称
            //getAuditEmployeeName  项目组
            //getRealAuditEmployeeName   真实审批人
            // connectType //0发起人1行政审批  只有0和1不展示（）中的项目名称，其余的需要展示
            //格式 环节名称（项目名称）
            if ("0".equals(entity.getConnectType()) || "1".equals(entity.getConnectType())) {
                tvProcessTitle.setText(entity.getWorkFlowName());
            } else {
                if (Utils.isNull(entity.getWorkFlowName())) {
                    tvProcessTitle.setText(entity.getWorkFlowName());
                    tvProcessTitleInit.setText(entity.getAuditEmployeeName());
                } else {
                    if (Utils.isNull(entity.getAuditEmployeeName())) {
                        tvProcessTitle.setText(entity.getWorkFlowName());
                        tvProcessTitleInit.setText("");
                    } else {
                        tvProcessTitle.setText(entity.getWorkFlowName());
                        tvProcessTitleInit.setText("(" + entity.getAuditEmployeeName() + ")");
                    }
                }
            }
            //1审核通过 2审核未通过0未审核3废弃
            if ("0".equals(entity.getAuditStatus())) {
                if ("0".equals(entity.getConnectType())) {
                    tvProcessStatus.setText("待修改");
                } else {
                    if (Utils.isNull(entity.getAuditEmployeeName())) {
                        tvProcessStatus.setText("待审批");
                    } else {
                        tvProcessTitleInit.setText("");
                        tvProcessStatus.setText("待" + entity.getAuditEmployeeName() + "审批");
                    }

                }
                tvProcessStatus.setTextColor(Color.parseColor("#FCA817"));
            } else if ("1".equals(entity.getAuditStatus())) {
                if ("0".equals(entity.getConnectType())) {
                    if (type == 8) {
                        if ("5".equals(entity.getParams().getStatusCd())) {
                            tvProcessStatus.setText("发起物品遗失申请");
                        } else if ("6".equals(entity.getParams().getStatusCd())) {
                            tvProcessStatus.setText("发起物品报废申请");
                        } else {
                            tvProcessStatus.setText("重新提交");
                        }
                    } else if (type == 9) {
                        if ("1".equals(entity.getParams().getRepaymentCd())) {
                            tvProcessStatus.setText("发起还款申请");
                        } else {
                            tvProcessStatus.setText("重新提交");
                        }
                    } else {
                        tvProcessStatus.setText("重新提交");
                    }
                } else {
                    if ("1".equals(entity.getReplaceCd())) {
                        //超管待审
                        tvProcessStatus.setText("超管代审批通过");
                    } else {
                        tvProcessStatus.setText("审批通过");
                    }

                }
                tvProcessStatus.setTextColor(Color.parseColor("#00C993"));
            } else {
                if ("3".equals(entity.getAuditStatus())) {
                    tvProcessStatus.setText("废弃");
                } else {
                    if ("1".equals(entity.getReplaceCd())) {
                        //超管待审
                        tvProcessStatus.setText("超管代审批不通过");
                    } else {
                        tvProcessStatus.setText("审批不通过");
                    }
                }
                tvProcessStatus.setTextColor(getResources().getColor(R.color.main_color));
            }
        }
    }
    private void passData(int auditStatus) {
        Map<String, Object> map = new HashMap<>();
        //1审核通过 2审核未通过0未审核
        Map<String, String> news = new HashMap<>();
        List<Map<String, String>> lists = new ArrayList<>();
        if (isRecord) {
            news.put("projectCode", projectCode);
            news.put("id", workflowId);
            news.put("employeeCode", clockInRecordEntity.getEmployeeCode());
        } else {
            news.put("projectCode", workNewEntity.getProjectCode());
            news.put("id", workNewEntity.getId());
            news.put("employeeCode", workNewEntity.getCreateEmployeeCode());
        }
        if(!Utils.isNull(edAudit.getText().toString())){
            news.put("remark", edAudit.getText().toString());
        }
        // 1-新闻 2-视频 3-补卡 4-请假 5-外勤 6-图文
        news.put("type", type + "");
        news.put("auditStatus", auditStatus + "");
        news.put("shangbanCd", shangbanCd + "");//1上班0下班

        lists.add(news);
        map.put("tbKmerWorkFlowProjects", XJson.listToJsArrays(lists));
        showLoading();
        MyHttpRequest.postRequestJson(Urls.auditWorkfolwProject, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("提交成功");
                        EventBus.getDefault().post(new MyEvent("RefreshClockInManagerExamine"));
                        finish();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("操作失败，请稍后重试");
                }
            }
        });
    }

    private void deleteData() {
        Map<String, String> map = new HashMap<>();
        map.put("workflowId", workflowId);
        map.put("qingjiaWorkflowCode", projectCode);
        map.put("workflowType", type + "");
        showLoading();
        MyHttpRequest.postRequest(Urls.deleteQingjiaInfo, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("提交成功");
                        EventBus.getDefault().post(new MyEvent("RefreshClockInManagerExamine"));
                        finish();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("提交失败，请稍后重试");
                }
            }
        });
    }

    @OnClick({R.id.common_title_back,  R.id.llProcess,R.id.common_right_txt, R.id.tvCancel, R.id.tvSure})
    public void onClick(View view) {
        Intent intent=null;
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.common_right_txt:
            case R.id.llProcess:
                if (Urls.antiShake.check()) {
                    return;
                }
                 intent = new Intent(this, ApprovalProcessActivity.class);
                if (isRecord) {
                    intent.putExtra("projectCode", projectCode);
                } else {
                    intent.putExtra("projectCode", workNewEntity.getProjectCode());
                }
                intent.putExtra("type", type);//3补卡 4请假5外勤
                intent.putExtra("shangbanCd", shangbanCd + "");//1上班0下班
                startActivity(intent);
                break;
            case R.id.tvCancel:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (tvCancel.getText().toString().equals("不通过")) {
                    passData(2);
                } else {
                    deleteData();
                }
                break;
            case R.id.tvSure:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (tvSure.getText().toString().equals("通过")) {
                    passData(1);
                } else {
                     intent = new Intent(this, ClockInReissueCardActivity.class);
                    intent.putExtra("clockInDetailEntity", clockInDetailEntity);
                    intent.putExtra("edit", true);
                    intent.putExtra("workflowType", type);
                    intent.putExtra("type", shangbanCd);
                    startActivity(intent);
                    finish();
                }
                break;
        }
    }
}
